<template>
  <div class="crm-page customer-add-page">
    <div class="page-header">{{ title }}客户</div>
    <div class="page-content transparent">
      <div class="page-card">
        <div class="card-title">
          <el-button class="back-btn" size="medium" type="text" icon="el-icon-back" @click="goMainBack()">返回</el-button>
        </div>
        <el-form ref="form" :model="form" label-width="100px" :rules="rules">
          <div class="page-card-content">
            <div class="item-title" style="margin-top:20px">
              基本信息
            </div>
            <div class="card-item">
              <el-row :gutter="10">
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="客户名" prop="name">
                    <el-input v-model="form.name" placeholder="请输入客户名" maxlength="50" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="客户编码" prop="code">
                    <el-input v-model="form.code" placeholder="根据规则自动生成" maxlength="50" disabled />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="行业" prop="industryId">
                    <el-select v-model="form.industryId" style="width:100%" placeholder="请选择行业">
                      <el-option v-for="cs in Industrys" :key="cs.value" :value="cs.value" :label="cs.label" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="客户级别" prop="level">
                    <el-select v-model="form.level" style="width:100%" placeholder="请选择客户级别">
                      <el-option v-for="cs in customerLevels" :key="cs.value" :value="cs.value" :label="cs.label" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="客户类型" prop="type">
                    <el-select v-model="form.type" style="width:100%" placeholder="请选择客户类型">
                      <el-option v-for="cs in customerTypes" :key="cs.value" :value="cs.value" :label="cs.label" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="客户所有人" prop="owner">
                    <el-input v-model="form.owner" placeholder="请输入客户所有人" disabled maxlength="50" readonly />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="员工数" prop="employeeNum">
                    <el-select v-model="form.employeeNum" style="width:100%" placeholder="请选择员工数">
                      <el-option v-for="cs in employees" :key="cs.value" :value="cs.value" :label="cs.label" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
          <div class="page-card-content">
            <div class="item-title" style="margin-top:20px">
              地址信息
            </div>
            <div class="card-item">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                  <el-form-item prop="invoiceList" label="开票地址">
                    <VbAreasForm v-model="form.invoiceList" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                  <el-form-item prop="receiveList" label="收货地址">
                    <VbAreasForm v-model="form.receiveList" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>

          <div class="page-card-content" style="padding-top:20px">
            <el-form-item prop="remark" label="备注">
              <el-input v-model="form.remark" type="textarea" :rows="3" maxlength="255" />
            </el-form-item>
          </div>
          <div class="page-card-content" style="padding-top:20px">
            <el-row style="text-align:right">
              <el-button plain @click="handleClose">取消</el-button>
              <el-button type="primary" @click="submitForm">保存</el-button>
            </el-row>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
// import RegionSelect from '@/components/RegionSelect'
import { getCustomer, saveCustomer, updateCustomer } from '@/api/customer'
import VbAreasForm from '@/components/VbAreasForm'
import { Industrys, customerLevels, customerTypes, employees } from '@/utils/enums'
import { formatTime } from '@/utils/tools'
export default {
  name: 'CustomerAdd',
  components: { VbAreasForm },
  data() {
    const validateReceiveList = (rule, value, callback) => {
      let pass = true
      if (this.form.receiveList && this.form.receiveList.length > 0) {
        this.form.receiveList.forEach(item => {
          if ((item.areas && item.areas.length !== 3) || !item.address) {
            pass = false
          }
        })
        if (!pass) {
          callback(new Error('地址不能有空'))
        } else {
          callback()
        }
      } else {
        callback(new Error('地址不能有空'))
      }
    }
    const validateInvoiceList = (rule, value, callback) => {
      let pass = true
      if (this.form.invoiceList && this.form.invoiceList.length > 0) {
        this.form.invoiceList.forEach(item => {
          if ((item.areas && item.areas.length !== 3) || !item.address) {
            pass = false
          }
        })
        if (!pass) {
          callback(new Error('地址不能有空'))
        } else {
          callback()
        }
      } else {
        callback(new Error('地址不能有空'))
      }
    }
    return {
      customerTypes,
      employees,
      customerLevels,
      Industrys,
      receiveList: [],
      form: {
        'email': '',
        'employeeNum': '',
        'industryId': '',
        'industryName': '',
        'invoiceList': [],
        'level': 1,
        'name': '',
        'phone': '',
        'receiveList': [],
        'remark': '',
        code: '',
        type: ''
      },
      rules: {
        name: [
          { required: true, message: '客户名不能为空', trigger: 'blur' }
        ],
        receiveList: [
          { validator: validateReceiveList, trigger: 'blur' }
        ],
        invoiceList: [
          { validator: validateInvoiceList, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '修改' : '新增'
    }

  },
  mounted() {
    const id = this.$route.query.id
    if (id) {
      getCustomer({ id }).then(res => {
        // 处理invoiceList
        // const t = new Date().getTime()
        let invoiceList = []
        let receiveList = []
        if (res.invoiceList) {
          invoiceList = res.invoiceList.map((m, i) => {
            m.areas = []
            // m.id = t + i
            if (m.province && m.city && m.county) {
              m.areas = [m.province, m.city, m.county]
            }
            return m
          })
        }
        if (res.receiveList) {
          receiveList = res.receiveList.map((m, i) => {
            m.areas = []
            // m.id = t + i
            if (m.province && m.city && m.county) {
              m.areas = [m.province, m.city, m.county]
            }
            return m
          })
        }

        console.log('receiveList:', res.invoiceList)

        this.form = {
          id,
          'email': res.email,
          'employeeNum': res.employeeNum,
          'industryId': res.industryId,
          'industryName': res.industryName,
          'invoiceList': invoiceList,
          'level': res.level,
          'name': res.name,
          'phone': res.phone,
          'receiveList': receiveList,
          'remark': res.remark,
          code: res.code,
          owner: res.owner,
          type: res.type
        }
      })
    } else {
      this.form.invoiceList.push({

        address: '',
        city: '',
        county: '',
        province: '',
        areas: []
      })
      this.form.receiveList.push({

        address: '',
        city: '',
        county: '',
        province: '',
        areas: []

      })
      this.form.owner = this.USER.userName
    }
  },
  methods: {
    formatTime,
    handleClose() {
      this.$router.back()
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 有id 是修改
          if (this.form.id) {
            updateCustomer(this.form).then(res => {
              console.log('updateCustomer:', res)
              this.$router.back(-1)
              this.$message({
                type: 'success',
                message: '修改成功'
              })
            }).catch(ex => {
              this.$message({
                type: 'error',
                message: ex.message || '修改失败'
              })
            })
          } else {
            saveCustomer(this.form).then(res => {
              this.$message({
                type: 'success',
                message: '新增成功'
              })
              this.$router.back(-1)
            }).catch(ex => {
              this.$message({
                type: 'error',
                message: ex.message || '新增失败'
              })
            })
          }
        }
      })
    }

  }
}
</script>
<style lang="scss">
.customer-add-page{
  .el-form-item--small.el-form-item{
  margin-bottom: 0;
}

}

</style>

